package com.quectel.sdk.quecentrance.entranceguard;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.quectel.sdk.quecentrance.AbstractQuecEntranceBaseClient;
import com.quectel.sdk.quecentrance.entranceguard.model.*;
import com.quectel.util.common.JacksonUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 在这里编写说明
 *
 * @author: rananxin
 * @email: ryan.ran@quectel.com
 * @date: 2022-10-19 11:01:00
 */
public class EntranceGuardClient extends AbstractQuecEntranceBaseClient {
    private static final Logger LOGGER = LoggerFactory.getLogger(EntranceGuardClient.class);

    private static final int SUCCESS_CODE = 200;

    /**
     * 添加员工
     * @param addPersonReq
     * @return
     */
    public Long addDeptPerson(AddDeptPersonReq addPersonReq) {
        final String path = "api/v1/user/add";

        String response = requester.post(path, addPersonReq);
        JsonNode respJson = JacksonUtils.parse(response);
        int code = respJson.get("code").asInt();
        if (code == SUCCESS_CODE) {
            LOGGER.debug("quec 门禁员工添加成功 {}", JacksonUtils.toJsonString(addPersonReq));
            return JacksonUtils.parse(response).get("data").get("id").asLong();
        } else if (code == 30002) {
            LOGGER.warn("quec 门禁员工添加失败，存在相似人员 {}", response);
        } else if (respJson.get("msg").asText().equals("The phone number has been registered.")) {
            LOGGER.warn("quec 门禁员工添加失败，电话号重复 {}", response);
            QueryUserReq queryUserReq = new QueryUserReq();
            queryUserReq.setType("1");
            List<QueryUserResp> queryUserResps = queryUserList(queryUserReq);
            QueryUserResp queryUserResp = queryUserResps.parallelStream().filter(o -> StringUtils.isNotBlank(o.getMobile()) && o.getMobile().equals(addPersonReq.getMobile())).findFirst().orElse(null);
            if (Objects.nonNull(queryUserResp)) {
                // 添加组 id
                List<Long> collect = queryUserResp.getGroups().parallelStream().map(QueryUserResp.GroupsCls::getId).collect(Collectors.toList());
                List<Long> notExistGroupIds = Arrays.stream(addPersonReq.getGroupIds()).parallel().filter(o -> !collect.contains(o)).collect(Collectors.toList());
                Boolean aBoolean = Boolean.TRUE;
                if (CollectionUtils.isNotEmpty(notExistGroupIds)) {
                    collect.addAll(notExistGroupIds);
                    UpdateDeptPersonReq updateDeptPersonReq = new UpdateDeptPersonReq();
                    updateDeptPersonReq.setId(queryUserResp.getId());
                    updateDeptPersonReq.setName(queryUserResp.getName());
                    updateDeptPersonReq.setGroupIds(collect);
                    aBoolean = updateDeptPerson(updateDeptPersonReq);
                }
                if (Boolean.TRUE.equals(aBoolean)) {
                    return queryUserResp.getId();
                }
            }
        }
        return null;
    }

    public Boolean updateDeptPerson(UpdateDeptPersonReq updateDeptPersonReq) {
        final String path = "api/v1/user/edit";

        String response = requester.post(path, updateDeptPersonReq);
        JsonNode respJson = JacksonUtils.parse(response);
        int code = respJson.get("code").asInt();
        if (code == SUCCESS_CODE) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 删除人员
     * @param personId
     * @return
     */
    public boolean delPerson(Integer personId) {
        final String path = "api/v1/user/delete";

        if (personId == null) {
            return Boolean.FALSE;
        }

        String response = requester.delete(path + "?id=" + personId, null);
        JsonNode respJson = JacksonUtils.parse(response);
        int code = respJson.get("code").asInt();
        if (code == SUCCESS_CODE) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 添加访客
     * @param addVisitorReq
     * @return
     */
    public Long addVisitor(AddVisitorReq addVisitorReq) {
        final String path = "api/v1/visitor/add";

        String response = requester.post(path, addVisitorReq);
        JsonNode respJson = JacksonUtils.parse(response);
        int code = respJson.get("code").asInt();
        if (code == SUCCESS_CODE) {
            LOGGER.debug("quec 门禁访客添加成功 {}", JacksonUtils.toJsonString(addVisitorReq));
            return JacksonUtils.parse(response).get("data").get("id").asLong();
        } else if (code == 30002) {
            LOGGER.warn("quec 门禁访客添加失败，存在相似人员 {}", response);
        }
        return null;
    }

    /**
     * 获取人员列表，按type 区分，包含员工和访客
     */
    public List<QueryUserResp> queryUserList(QueryUserReq queryUserReq) {
        final String path = "api/v1/user/list";

        Map<String, Object> params = BeanUtil.beanToMap(queryUserReq);
        params.entrySet().removeIf(entry -> entry.getValue() == null);
        String response = requester.get(path, params);
        JsonNode respJson = JacksonUtils.parse(response);
        JsonNode code = respJson.get("code");
        if (code == null) {
            // 这里特殊，数据没按文档的返回
            return JacksonUtils.parseArray(response, QueryUserResp.class);
        }
        return Lists.newArrayList();
    }

    /**
     * 获取组列表, 按 type 区分 1员工组，2访客组，5黑名单组
     */
    public List<QueryGroupResp> queryGroupList(QueryGroupReq queryGroupReq) {
        final String path = "api/v1/group/list";

        Map<String, Object> params = BeanUtil.beanToMap(queryGroupReq);
        params.entrySet().removeIf(entry -> entry.getValue() == null);
        String response = requester.get(path, params);
        JsonNode respJson = JacksonUtils.parse(response);
        Integer code = respJson.get("code").asInt();
        if (code == SUCCESS_CODE) {
            // 这里特殊，数据没按文档的返回
            return JacksonUtils.parseArray(JacksonUtils.toJsonString(respJson.get("data")), QueryGroupResp.class);
        }
        return Lists.newArrayList();
    }

    /**
     * 添加访客
     * @param addGroupReq
     * @return
     */
    public Integer addGroup(AddGroupReq addGroupReq) {
        final String path = "api/v1/group/add";

        String response = requester.post(path, addGroupReq);
        JsonNode respJson = JacksonUtils.parse(response);
        int code = respJson.get("code").asInt();
        if (code == SUCCESS_CODE) {
            LOGGER.debug("quec 门禁组添加成功 {}", JacksonUtils.toJsonString(addGroupReq));
            return JacksonUtils.parse(response).get("data").get("id").asInt();
        }
        return null;
    }

    /**
     * 删除组
     * @param groupId
     * @return
     */
    public boolean delGroup(Integer groupId) {
        final String path = "api/v1/group/delete";

        if (groupId == null) {
            return Boolean.FALSE;
        }

        String response = requester.delete(path + "?id=" + groupId, null);
        JsonNode respJson = JacksonUtils.parse(response);
        int code = respJson.get("code").asInt();
        if (code == SUCCESS_CODE) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    /**
     * 获取设备列表
     */
    public List<QueryDeviceResp> queryDeviceList(QueryDeviceReq queryDeviceReq) {
        final String path = "api/v1/device/list";

        Map<String, Object> params = BeanUtil.beanToMap(queryDeviceReq);
        params.entrySet().removeIf(entry -> entry.getValue() == null);
        String response = requester.get(path, params);
        JsonNode respJson = JacksonUtils.parse(response);
        Integer code = respJson.get("code").asInt();
        if (code == SUCCESS_CODE) {
            // 这里特殊，数据没按文档的返回
            return JacksonUtils.parseArray(JacksonUtils.toJsonString(respJson.get("data")), QueryDeviceResp.class);
        }
        return Lists.newArrayList();
    }

    /**
     * 头像上传
     */
    public String uploadAvatar(File file) {
        final String path = "api/v1/user/person";

        if (file == null) {
            return null;
        }
        HttpResponse response = HttpUtil.createPost(requester.genUrl(path))
                .addHeaders(requester.genHeader())
                .form("file", file)
                .execute();
        if (response.getStatus() == 200
                && JacksonUtils.parse(response.body()).get("code").asInt() == SUCCESS_CODE) {
            return JacksonUtils.parse(response.body()).get("url").asText();
        }
        return null;
    }
}
